import React, { useState, useEffect } from 'react';
import Taro, { useReachBottom, usePullDownRefresh } from '@tarojs/taro';
import { View, Text, ScrollView } from '@tarojs/components';
import request from '@/utils/utils.js';
import './index.module.scss';

export default function RecordPage() {
  const [transactions, setTransactions] = useState([]);
  const [page, setPage] = useState(1);
  const [hasMore, setHasMore] = useState(true);
  const [isLoading, setIsLoading] = useState(false);

  useEffect(() => {
    loadTransactions();
  }, []);

  useReachBottom(() => {
    if (hasMore && !isLoading) {
      loadTransactions(page + 1);
    }
  });

  usePullDownRefresh(() => {
    setTransactions([]);
    setPage(1);
    setHasMore(true);
    loadTransactions(1, true);
  });

  const loadTransactions = async (pageNum = 1, isPullDownRefresh = false) => {
    setIsLoading(true);
    const userId = Taro.getStorageSync('userId');
    const currentYear = new Date().getFullYear();
    const startDate = `${currentYear}-01-01`;
    const endDate = `${currentYear}-12-31`;

    try {
      const result = await request({
        url: `http://43.143.236.218:8080/transactions`,
        method: 'GET',
        data: {
          user_id: userId,
          page: pageNum,
          page_size: 20,
          start_date: startDate,
          end_date: endDate
        }
      });

      if (result.success) {
        const newTransactions = result?.data || [];
        setTransactions(prev => (pageNum === 1 ? newTransactions : [...prev, ...newTransactions]));
        setPage(pageNum);
        setHasMore(newTransactions.length === 20);
      } else {
        Taro.showToast({
          title: '加载失败',
          icon: 'none',
          duration: 2000
        });
      }
    } catch (error) {
      console.error('Error fetching transactions:', error);
      Taro.showToast({
        title: '加载失败，请重试',
        icon: 'none',
        duration: 2000
      });
    } finally {
      setIsLoading(false);
      if (isPullDownRefresh) {
        Taro.stopPullDownRefresh();
      }
    }
  };

  const formatDate = (dateString) => {
    const date = new Date(dateString);
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
  };

  return (
    <View className='expense-tracker-record'>
      {/* Header Section */}
      <View className='header'>
        <View className='nav-title'>记账历史</View>
      </View>

      {/* Main Content Section */}
      <View className='main'>
        <ScrollView
          className='record-content'
          scrollY
          scrollWithAnimation
          enableBackToTop
          enableFlex
        >
          {transactions.map((transaction, index) => (
            <View key={index} className='transaction-item'>
              <View className='transaction-info'>
                <View className='category-wrapper'>
                  <Text className='category'>{transaction.category}</Text>
                </View>
                <Text className='date'>{formatDate(transaction.date)}</Text>
              </View>
              <Text className='amount'>¥{transaction.amount.toFixed(2)}</Text>
            </View>
          ))}
          
          {isLoading && (
            <View className='loading-state'>加载中...</View>
          )}
          
          {!hasMore && (
            <View className='loading-state'>没有更多数据了</View>
          )}
        </ScrollView>
      </View>

      {/* Footer Section */}
      <View className='footer'>
        <View 
          className='footer-btn'
          onClick={() => Taro.navigateTo({ url: '/pages/index/index' })}
        >
          记账
        </View>
        <View className='footer-btn active'>历史</View>
        <View className='footer-btn' onClick={() => Taro.navigateTo({ url: '/pages/my/index' })}>我的</View>
      </View>
    </View>
  );
}